package Kuaishou;

import java.util.List;

import org.apache.commons.compress.utils.Lists;

import lombok.Data;

/**
 * @author leiwenkang <leiwenkang@kuaishou.com>
 * Created on 2020-08-07
 */
public class Test01二分法 {
    public static void main(String[] args) {
        List<StockPvInfo> pvQueryResult = Lists.newArrayList();
        StockPvInfo stockPvInfo = new StockPvInfo();
        stockPvInfo.setPvTotal(200);
        stockPvInfo.setPvRemain(100);

        pvQueryResult.add(stockPvInfo);

        new Test01二分法().calculateSupplyAndServiceRate(pvQueryResult, 30, 0.2);

    }

    //类似于二分查找，寻找m值，使得s刚好大于quantity（不超过100000即可）
    public void calculateSupplyAndServiceRate(List<StockPvInfo> pvQueryResult,
            long quantity, double breakageRatio) {
        // 二分法 id, uv_remain map;
        long supply = 0;
        double l = 0.00, m = 0.00, r = 1.00; // 对每天求服务率,遍历每一天
        while (r - l > 1e-6) {
            m = (l + r) / 2.0; // 服务率
            long s = 0;
            for (StockPvInfo stockPvInfo : pvQueryResult) {
                s += Math.min((long) (stockPvInfo.getPvTotal() * breakageRatio) * m, stockPvInfo.getPvRemain());
            }
            if (s > quantity && (s - quantity <= 10000)) {
                supply = s;
                break;
            }
            if (s < quantity) {
                l = m;
            } else if (s > quantity) {
                r = m;
            } else {
                supply = s;
                break;
            }
            supply = s;
        }
        System.out.println(supply);
        System.out.println(m);
    }
}

@Data
class StockPvInfo {
    private int pvTotal;
    private int pvRemain;
}
